package com.alumni_circle.core.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * JSON登录
 *
 * @author  龙小虬
 * @create  2020-08-07 15:01
 **/
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //json请求
        if (!StrUtil.hasEmpty(request.getContentType()) && request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {

            //使用jackson设置userdetails
            UsernamePasswordAuthenticationToken authRequest = null;
            ObjectMapper objectMapper = new ObjectMapper();
            try (InputStream is = request.getInputStream()) {
                Map map = objectMapper.readValue(is,Map.class);
                authRequest = new UsernamePasswordAuthenticationToken(
                        map.get("username"), map.get("password"));
            } catch (IOException e) {
                e.printStackTrace();
                authRequest = new UsernamePasswordAuthenticationToken(
                        "", "");
            }
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
        }
        //调用父类的attemptAuthentication
        else {
            return super.attemptAuthentication(request, response);
        }
    }
}